<template>
  <div 
    class="stream-debugger" 
    v-if="showDebugger"
    :style="{ top: position.y + 'px', left: position.x + 'px' }"
    @mousedown="startDrag"
  >
    <div class="debugger-header">
      <h3>流式数据调试器</h3>
      <button @click="toggleDebugger" class="toggle-button">
        {{ isExpanded ? '收起' : '展开' }}
      </button>
      <button @click="clearLogs" class="clear-button">清空</button>
      <button @click="showDebugger = false" class="close-button">×</button>
    </div>
    
    <div class="debugger-content" v-if="isExpanded">
      <div class="debug-stats">
        <div class="stat-item">
          <span class="stat-label">总块数:</span>
          <span class="stat-value">{{ totalChunks }}</span>
        </div>
        <div class="stat-item">
          <span class="stat-label">累积字符:</span>
          <span class="stat-value">{{ totalCharacters }}</span>
        </div>
        <div class="stat-item">
          <span class="stat-label">思考字符:</span>
          <span class="stat-value">{{ thinkingCharacters }}</span>
        </div>
        <div class="stat-item">
          <span class="stat-label">回答字符:</span>
          <span class="stat-value">{{ actualCharacters }}</span>
        </div>
      </div>
      
      <div class="debug-logs">
        <div class="logs-header">
          <span>数据流日志</span>
          <label class="auto-scroll-toggle">
            <input type="checkbox" v-model="autoScroll">
            自动滚动
          </label>
        </div>
        <div class="logs-content" ref="logsRef">
          <div 
            v-for="(log, index) in logs" 
            :key="index"
            class="log-entry"
            :class="log.type"
          >
            <span class="log-timestamp">{{ formatTimestamp(log.timestamp) }}</span>
            <span class="log-type">{{ log.type.toUpperCase() }}</span>
            <span class="log-content">{{ log.content }}</span>
            <div v-if="log.metadata" class="log-metadata">
              <pre>{{ JSON.stringify(log.metadata, null, 2) }}</pre>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
  
  <!-- 调试器触发按钮 -->
  <button 
    v-if="!showDebugger" 
    @click="showDebugger = true" 
    class="debug-trigger"
    title="打开流式数据调试器"
  >
    🕸️
  </button>
</template>

<script setup>
import { ref, computed, watch, nextTick, onMounted, onUnmounted } from 'vue'

const props = defineProps({
  enabled: {
    type: Boolean,
    default: false
  }
})

// 状态
const showDebugger = ref(props.enabled)
const isExpanded = ref(true)
const autoScroll = ref(true)
const logs = ref([])
const logsRef = ref(null)

// 拖拽相关状态
const position = ref({ x: 20, y: window.innerHeight - 520 })
const isDragging = ref(false)
const dragOffset = ref({ x: 0, y: 0 })

// 统计信息
const totalChunks = computed(() => logs.value.filter(log => log.type === 'chunk').length)
const totalCharacters = computed(() => {
  const lastLog = logs.value.filter(log => log.type === 'chunk').pop()
  return lastLog?.accumulatedLength || 0
})
const thinkingCharacters = computed(() => {
  const lastLog = logs.value.filter(log => log.type === 'chunk').pop()
  return lastLog?.thinkingLength || 0
})
const actualCharacters = computed(() => {
  const lastLog = logs.value.filter(log => log.type === 'chunk').pop()
  return lastLog?.actualLength || 0
})

// 方法
const toggleDebugger = () => {
  isExpanded.value = !isExpanded.value
}

const clearLogs = () => {
  logs.value = []
}

const addLog = (type, content, metadata = null, extra = {}) => {
  logs.value.push({
    type,
    content,
    metadata,
    timestamp: Date.now(),
    ...extra
  })
  
  if (autoScroll.value) {
    nextTick(() => {
      scrollToBottom()
    })
  }
}

const scrollToBottom = () => {
  if (logsRef.value) {
    logsRef.value.scrollTop = logsRef.value.scrollHeight
  }
}

const formatTimestamp = (timestamp) => {
  const date = new Date(timestamp)
  return date.toLocaleTimeString('zh-CN', { 
    hour12: false,
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
    fractionalSecondDigits: 3
  })
}

// 拖拽相关方法
const startDrag = (event) => {
  // 如果点击的是按钮，不启动拖拽
  if (event.target.tagName === 'BUTTON' || 
      event.target.closest('button') || 
      event.target.closest('.logs-content')) {
    return
  }
  
  isDragging.value = true
  dragOffset.value = {
    x: event.clientX - position.value.x,
    y: event.clientY - position.value.y
  }
  
  document.addEventListener('mousemove', onDrag)
  document.addEventListener('mouseup', stopDrag)
}

const onDrag = (event) => {
  if (isDragging.value) {
    position.value = {
      x: event.clientX - dragOffset.value.x,
      y: event.clientY - dragOffset.value.y
    }
  }
}

const stopDrag = () => {
  isDragging.value = false
  document.removeEventListener('mousemove', onDrag)
  document.removeEventListener('mouseup', stopDrag)
}

// 组件挂载和卸载时的事件处理
onMounted(() => {
  // 确保调试器初始位置在视窗内
  position.value = {
    x: Math.min(window.innerWidth - 420, Math.max(20, position.value.x)),
    y: Math.min(window.innerHeight - 520, Math.max(20, position.value.y))
  }
})

onUnmounted(() => {
  document.removeEventListener('mousemove', onDrag)
  document.removeEventListener('mouseup', stopDrag)
})

// 公开的方法供父组件调用
const logStreamStart = (sessionId) => {
  addLog('start', `开始流式请求 - 会话: ${sessionId}`)
}

const logStreamChunk = (chunk) => {
  const content = `接收数据块: "${chunk.content}" (${chunk.content?.length || 0} 字符)`
  addLog('chunk', content, chunk.metadata, {
    accumulatedLength: chunk.accumulatedContent?.length || 0,
    thinkingLength: chunk.thinkingContent?.length || 0,
    actualLength: chunk.actualContent?.length || 0,
    isInThinkingMode: chunk.isInThinkingMode
  })
}

const logStreamComplete = (finalData) => {
  addLog('complete', `流式响应完成 - 总计: ${finalData.content?.length || 0} 字符`, finalData.metadata)
}

const logStreamError = (error) => {
  addLog('error', `流式响应错误: ${error.message}`)
}

const logMessage = (message, type = 'info') => {
  addLog(type, message)
}

// 监听自动滚动变化
watch(autoScroll, (newValue) => {
  if (newValue) {
    nextTick(() => {
      scrollToBottom()
    })
  }
})

defineExpose({
  logStreamStart,
  logStreamChunk,
  logStreamComplete,
  logStreamError,
  logMessage,
  clearLogs
})
</script>

<style scoped>
.stream-debugger {
  position: fixed;
  width: 400px;
  max-height: 500px;
  background: white;
  border: 1px solid #ddd;
  border-radius: 8px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
  z-index: 1000;
  font-family: monospace;
  font-size: 12px;
  cursor: move;
}

.debugger-header {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 12px;
  background: #f8f9fa;
  border-bottom: 1px solid #ddd;
  border-radius: 8px 8px 0 0;
}

.debugger-header h3 {
  margin: 0;
  font-size: 14px;
  font-weight: 600;
  color: #333;
  flex: 1;
}

.toggle-button,
.clear-button,
.close-button {
  background: none;
  border: 1px solid #ddd;
  border-radius: 4px;
  padding: 4px 8px;
  cursor: pointer;
  font-size: 11px;
  transition: all 0.2s;
}

.toggle-button:hover,
.clear-button:hover {
  background: #e9ecef;
}

.close-button {
  color: #dc3545;
  border-color: #dc3545;
  background: #f8f9fa;
  font-weight: bold;
  width: 24px;
  height: 24px;
  padding: 0;
  display: flex;
  align-items: center;
  justify-content: center;
}

.close-button:hover {
  background: #dc3545;
  color: white;
}

.debugger-content {
  max-height: 400px;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.debug-stats {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 8px;
  padding: 8px 12px;
  background: #f8f9fa;
  border-bottom: 1px solid #ddd;
}

.stat-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.stat-label {
  color: #666;
  font-size: 11px;
}

.stat-value {
  color: #007bff;
  font-weight: bold;
}

.debug-logs {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-height: 0;
}

.logs-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 12px;
  background: #f1f3f4;
  border-bottom: 1px solid #ddd;
  font-weight: 600;
  color: #333;
}

.auto-scroll-toggle {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 11px;
  font-weight: normal;
  cursor: pointer;
}

.logs-content {
  flex: 1;
  overflow-y: auto;
  padding: 8px;
  max-height: 250px;
}

.logs-content::-webkit-scrollbar {
  width: 4px;
}

.logs-content::-webkit-scrollbar-track {
  background: #f1f1f1;
}

.logs-content::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 2px;
}

.log-entry {
  margin-bottom: 8px;
  padding: 6px;
  border-radius: 4px;
  border-left: 3px solid #ddd;
}

.log-entry.start {
  background: #e3f2fd;
  border-left-color: #2196f3;
}

.log-entry.chunk {
  background: #f8f0fc;
  border-left-color: #ae3ec9;
}

.log-entry.complete {
  background: #e8f5e8;
  border-left-color: #4caf50;
}

.log-entry.error {
  background: #ffebee;
  border-left-color: #f44336;
}

.log-entry.info {
  background: #fff3e0;
  border-left-color: #ff9800;
}

.log-timestamp {
  color: #666;
  font-size: 10px;
  margin-right: 8px;
}

.log-type {
  font-weight: bold;
  margin-right: 8px;
  font-size: 10px;
}

.log-type.START { color: #2196f3; }
.log-type.CHUNK { color: #9c27b0; }
.log-type.COMPLETE { color: #4caf50; }
.log-type.ERROR { color: #f44336; }
.log-type.INFO { color: #ff9800; }

.log-content {
  color: #333;
  word-break: break-word;
}

.log-metadata {
  margin-top: 4px;
  padding: 4px;
  background: rgba(0, 0, 0, 0.05);
  border-radius: 2px;
  font-size: 10px;
}

.log-metadata pre {
  margin: 0;
  color: #666;
  white-space: pre-wrap;
  word-break: break-word;
}

.debug-trigger {
  position: fixed;
  top: 20px;
  right: 80px;
  width: 24px;
  height: 24px;
  border: 1px solid #ddd;
  border-radius: 4px;
  background: #f8f9fa;
  color: #333;
  font-size: 11px;
  cursor: pointer;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  z-index: 999;
  transition: all 0.2s;
  display: flex;
  align-items: center;
  justify-content: center;
}

.debug-trigger:hover {
  background: #e9ecef;
  border-color: #007bff;
  color: #007bff;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .stream-debugger {
    width: calc(100vw - 40px);
    max-width: 350px;
  }
  
  .debug-trigger {
    top: 10px;
    right: 60px;
    width: 24px;
    height: 24px;
    font-size: 11px;
  }
}

/* 用户聊天气泡样式 - 浅色 */
.log-entry.chunk {
  background: #f0f7ff;
  border-left-color: #69a3ff;
}
</style>